package com.book.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.book.domain.Product;
import com.book.domain.User;
import com.book.util.DBUtil;
import com.sun.org.apache.regexp.internal.recompile;

public class CartDao {

	public void addProduct(Product product){
	Connection connection=	DBUtil.getConnection();
	String sql="insert into t_cart(userid,bookname,bookprice,bookcount,booksprice,productid) values(?,?,?,?,?,?)";	
	PreparedStatement preparedStatement=null;
	try {
		preparedStatement=connection.prepareStatement(sql);
		preparedStatement.setInt(1, product.getUserid());
		preparedStatement.setString(2, product.getBookname());
		preparedStatement.setFloat(3, product.getBookprice());
		preparedStatement.setInt(4, product.getBookcount());
		preparedStatement.setFloat(5,product.getBooksprice());
		preparedStatement.setInt(6, product.getProductid());
		
		preparedStatement.executeUpdate();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	}
	public List<Product> getAllProducts(User user){
		List<Product> products=new ArrayList<Product>();
	    Connection connection=	DBUtil.getConnection();
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		String sql="select  userid,bookname,bookprice,COUNT(bookcount) as bookcount,sum(bookprice) as booksprice from t_cart where userid=? group by productid,userid,bookname,bookprice";
	    try {
			preparedStatement=	connection.prepareStatement(sql);
		    preparedStatement.setInt(1, user.getId());
		    resultSet=preparedStatement.executeQuery();
		    while (resultSet.next()) {
				Product product=new Product(0,resultSet.getInt("userid"),resultSet.getString("bookname"),resultSet.getFloat("bookprice"),resultSet.getInt("bookcount"),resultSet.getFloat("booksprice"));
				System.out.println(product);
				products.add(product);
			}
	    } catch (SQLException e) {
			e.printStackTrace();
		}
		return products;
	}
}
